package 极客算法训练营.chapter07;

import java.util.ArrayList;
import java.util.List;

public class 括号生成 {
    class Solution {

        private List<String> result;

        public List<String> generateParenthesis(int n) {
            result = new ArrayList<>();
            backtrack("", 0, 0, n);
            return result;
        }

        private void backtrack(String str, int left, int right, int n) {
            //结束条件
            if (left == n && right == n) {
                result.add(str);
                return;
            }
            //加左括号
            if (left < n) {
                backtrack(str + "(", left + 1, right, n);
            }
            //加右括号
            if (right < left) {
                backtrack(str + ")", left, right + 1, n);
            }
        }
    }
}
